<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="newName" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="newAge" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="newSex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click.prevent="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click.prevent="del(item.id)">删除</button>
            <button @click.prevent="change(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      newName: "",
      newAge: "",
      newSex: "",
      flag: "",
      list: [
        {
          id: 1,
          name: "Tom",
          age: 18,
          sex: "男",
        },

        {
          id: 2,
          name: "Jone",
          age: 18,
          sex: "男",
        },
      ],
    };
  },

  methods: {
    add() {
      if (
        this.newName.trim().length === 0 ||
        this.newAge <= 0 ||
        this.newSex.length === 0
      )
        return alert("内容不能为空");

      if (!this.flag) {
        this.list.push({
          id: +new Date(),
          name: this.newName,
          age: this.newAge,
          sex: this.newSex,
        });
      } else {
        this.flag.name = this.newName;
        this.flag.sex = this.newSex;
        this.flag.age = this.newAge;
      }
      this.newName = "";
      this.newAge = "";
      this.newSex = "";
      this.flag = "";
    },

    del(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },

    change(id) {
      let obj = this.list.find((item) => item.id === id);

      this.flag = obj;
      this.newName = obj.name;
      this.newAge = obj.age;
      this.newSex = obj.sex;
    },
  },
};
</script>